from django.shortcuts import render, redirect
from aj.jgdw import model_form2
from django.http import JsonResponse
from aj import models
from aj.jgdw.page import Pagination
from django.db.models import Q
from django_pandas.io import read_frame
import pandas as pd


# 返回obj
def get_obj(request):
    obj1 = models.UserInfo.objects.filter(is_superuser=False).values('name','sfzhm','xueli','junren','falv','bzlx','gzbz','organization__xingzhengquhua__shi','organization__xingzhengquhua__xian')
    obj2 = models.Organization.objects.filter(sj__isnull=False).values('bianzhi', 'gaopei', 'sj', 'dwxz', 'che',
                                                                       'jingfei', 'xingzhengquhua__shi',
                                                                       'xingzhengquhua__xian')
    # if request.use    r.level == '1':  # 省级
    #     pass
    # if request.user.level == '2':  # 市级
    #     QQ1 = Q(organization=request.user.organization) | Q(
    #         organization__sj=request.user.organization.id)
    #     QQ2 = Q(id=request.user.organization.id) | Q(sj=request.user.organization.id)
    #     obj1 = obj1.filter(QQ1)
    #     obj2 = obj2.filter(QQ2)
    # if request.user.level == '3':  # 县级
    #     obj1 = obj1.filter(organization=request.user.organization)
    #     obj2 = obj1.filter(id=request.user.organization.id)
    return obj1, obj2


def get_index_df(obj1, obj2):
    obj = {}
    df_id = pd.DataFrame({'shi': ['郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市',
                                  '南阳市', '商丘市', '信阳市', '周口市', '驻马店市', '济源市', '巩义市', '兰考县', '汝州市', '滑县', '长垣市', '邓州市',
                                  '永城市', '固始县', '鹿邑县', '新蔡县'],
                          'jx': ['郑州', '开封', '洛阳', '平顶山', '安阳', '鹤壁', '新乡', '焦作', '濮阳', '许昌', '漯河', '三门峡', '南阳', '商丘',
                                 '信阳', '周口', '驻马店', '济源', '巩义', '兰考', '汝州', '滑县', '长垣', '邓州', '永城', '固始', '鹿邑', '新蔡'],
                          'bj': range(28)})
    df1 = read_frame(obj1)  # 人员
    df2 = read_frame(obj2)  # 机构
    # 机构数高配数
    df_jgs = df2.pivot_table(index='xingzhengquhua__shi', values='xingzhengquhua__xian', aggfunc='count')
    df_gps = df2.pivot_table(index='xingzhengquhua__shi', columns='gaopei', values='xingzhengquhua__xian',
                             aggfunc='count', fill_value=0)
    pic1 = df_id.merge(df_jgs, left_on='shi', right_on='xingzhengquhua__shi', how='left').merge(df_gps,left_on='shi',right_on='xingzhengquhua__shi',how='left').sort_values('bj')
    pic1=pic1[['jx','xingzhengquhua__xian','是']].to_dict(orient='split')
    obj['pic1'] = pic1

    #经费车辆
    df_jf1=df2[df2['sj']=='河南省农业综合行政执法监督局'].pivot_table(index='xingzhengquhua__shi',values='jingfei',aggfunc='sum').rename(columns={'jingfei':'jingfei_shi'})
    df_jf2=df2[df2['sj']!='河南省农业综合行政执法监督局'].pivot_table(index='xingzhengquhua__shi',values='jingfei',aggfunc='sum').rename(columns={'jingfei':'jingfei_xian'})
    df_che=df2.pivot_table(index='xingzhengquhua__shi',values='che',aggfunc='sum')
    pic2=df_id.merge(df_jf1,left_on='shi',right_on='xingzhengquhua__shi',how='left')\
        .merge(df_jf2,left_on='shi',right_on='xingzhengquhua__shi',how='left')\
        .merge(df_che,left_on='shi',right_on='xingzhengquhua__shi',how='left').fillna(0).sort_values('bj')
    obj['pic2'] = pic2[['jx','jingfei_shi','jingfei_xian','che']].to_dict(orient='split')
    obj['max_jf']=(int(max(pic2['jingfei_shi']+pic2['jingfei_xian'])/10)+1)*10
    obj['max_che']=(int(max(pic2['che'])/10)+1)*10

    #编制，在岗
    df_bzrs=df2.pivot_table(index='xingzhengquhua__shi',values='bianzhi',aggfunc='sum')
    df_zgrs=df1.pivot_table(index='organization__xingzhengquhua__shi',values='name',aggfunc='count')
    pic3=df_id.merge(df_bzrs,how='left',left_on='shi',right_on='xingzhengquhua__shi').\
        merge(df_zgrs,how='left',left_on='shi',right_on='organization__xingzhengquhua__shi').sort_values('bj').fillna(0)
    obj['pic3']=pic3[['jx','bianzhi','name']].to_dict(orient='split')
    obj['pic3_max']=(int(max(max(pic3['bianzhi']),max(pic3['name']))/100)+1)*100
    return obj

# 首页
def index(request):
    if request.user.category == '1':  # 管理员
        obj = get_obj(request)
        obj = get_index_df(obj[0], obj[1])
        return render(request, 'html模板/机构队伍index.html', locals())
    else:
        return redirect('/edit_grxx')


# 单位列表
def org_list(request):
    if request.user.category == '1':  # 管理员
        user = request.user
        obj = models.Organization.objects.all()
        if user.level == '1':  # 省级管理员
            obj = obj
        elif user.level == '2':  # 市级管理员
            QQ = Q(id=user.organization.id) | Q(sj_id=user.organization.id)
            print(user.organization)
            obj = obj.filter(QQ)
        else:  # 县级管理员
            obj = obj.filter(id=user.organization.id)
        current_page = request.GET.get('p')
        page_obj = Pagination(obj.count(), current_page, perPageItemNum=20, qianzhui='jglb', maxPageNum=9)
        list = obj[page_obj.start():page_obj.end()]
        return render(request, 'html模板/机构队伍单位列表.html', locals())
    else:
        return redirect('/index/2/')


# 人员列表
def ry_list(request):
    if request.user.category == '1':  # 管理员
        user = request.user
        obj = models.UserInfo.objects.filter(is_superuser=False)
        if user.level == '2':  # 市级管理员
            QQ = Q(organization=user.organization) | Q(organization__sj=user.organization)
            obj = models.UserInfo.objects.filter(QQ)
        elif user.level == '3':  # 县级管理员
            obj = models.UserInfo.objects.filter(organization=user.organization)
        elif user.level == '1':
            obj = obj
        current_page = request.GET.get('p')
        page_obj = Pagination(obj.count(), current_page, perPageItemNum=20, qianzhui='rylb', maxPageNum=9)
        list = obj[page_obj.start():page_obj.end()]
        return render(request, 'html模板/机构队伍人员列表.html', locals())
    else:
        return redirect('/edit_grxx')


# 注册
def regist(request):
    obj = model_form2.Regist_form(request)
    if request.method == "POST":
        obj = model_form2.Regist_form(request, request.POST)
        if obj.is_valid():
            clean_data = obj.cleaned_data
            clean_data.pop('xzqh')
            clean_data['username'] = clean_data.get('phone')
            clean_data['category'] = '2'
            models.UserInfo.objects.create(**clean_data)
            return redirect('/index/1/')
    return render(request, 'html模板/机构队伍执法人员注册.html', locals())


# 编辑注册信息
def edit_grxx(request):
    obj = model_form2.Regist_form(request, instance=request.user)
    if request.method == "POST":
        obj = model_form2.Regist_form(request, request.POST, instance=request.user)
        if obj.is_valid():
            clean_data = obj.cleaned_data
            clean_data.pop('xzqh')
            models.UserInfo.objects.filter(id=request.user.id).update(**clean_data)
            return redirect('/index/2/')
    return render(request, 'html模板/机构队伍执法人员编辑.html', locals())


# 判断用户权限
def pdyhqx(request, id):
    # 当前用户
    dqyh = request.user
    # 要操作的用户
    mbyh = models.UserInfo.objects.filter(id=id).first()
    if mbyh:
        if dqyh.category == '1' and mbyh.category != '1' and (
                dqyh.organization == mbyh.organization or dqyh.organization.id == mbyh.organization.sj_id):  # 县级管理员
            return True
    return False


# 审核通过
def zfry_shtg(request, id):
    ret = {}
    level = request.user.level
    if pdyhqx(request, id):
        obj = models.UserInfo.objects.filter(id=id).update(level=level)
        if obj:
            ret['status'] = 200
            return JsonResponse(ret)
    ret['status'] = 400
    return JsonResponse(ret)


# 审核不通过
def zfry_shbtg(request, id):
    ret = {}
    if pdyhqx(request, id):
        models.UserInfo.objects.filter(id=id).update(level='')
        ret['status'] = 200
        return JsonResponse(ret)
    ret['status'] = 400
    return JsonResponse(ret)


# 编辑单位信息 只有管理员由此功能
def edit_dwxx(request):
    if request.user.category == '1':  # 管理员
        obj = model_form2.Organization_form(request, instance=request.user.organization)
        if request.method == "POST":
            obj = model_form2.Organization_form(request, request.POST, instance=request.user.organization)
            if obj.is_valid():
                obj.save()
                return redirect('/index/2/')
        return render(request, 'html模板/机构队伍编辑单位信息.html', locals())
